﻿using Aliyun.OSS;
using Kjs.Report.Model.Extensions;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Kjs.Report.Infrastructure
{
    public class OssFileUpload
    {
        private string _bucketName;
        private OssClient _client = null;

        public OssFileUpload(ApiUrls apiUrls)
        {
            _bucketName = apiUrls.OssBucket;
            _client = new OssClient(apiUrls.OssEndpoint, apiUrls.OssAccessKey, apiUrls.OssAccessSecret);
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="oldUrl">历史文件</param>
        /// <param name="file">文件流</param>
        /// <param name="fileExtName">文件扩展名</param>
        /// <param name="fileDir">文件目录</param>
        /// <param name="fileLength">文件大小</param>
        /// <returns></returns>

        public async Task<string> PutObject(string oldUrl, IFormFile file, string fileExtName, string fileDir, long fileLength)
        {
            var fileContentType = file.ContentType;
            using (var fileStream = file.OpenReadStream())
            {
                string key = fileDir + Guid.NewGuid().ToString() + "." + fileExtName;
                var metaData = new ObjectMetadata
                {
                    ContentType = fileContentType,
                    CacheControl = "no-cache",
                    ContentEncoding = "utf-8",
                    ContentLength = fileLength,
                };

                var putObj = new PutObjectRequest(_bucketName, key, fileStream, metaData);
                var result = await _client.PutObjectAsync(putObj);

                if (result.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    var url = GetUrl(key);
                    if (!string.IsNullOrWhiteSpace(oldUrl))
                    {
                        var oldKey = new Uri(oldUrl).LocalPath.TrimStart('/');
                        _client.DeleteObject(_bucketName, oldKey);   //上传新图片 删除上一张图片
                    }
                    return url;
                }
            }
            return "";
        }

        public void DeleteObject(string imgUrl)
        {
            string key = "";
            if (imgUrl.Contains("http") || imgUrl.Contains("https"))
            {
                key = new Uri(imgUrl).LocalPath.TrimStart('/');
            }
            else
            {
                key = imgUrl.TrimStart('/');
            }
            _client.DeleteObject(_bucketName, key);
        }

        public void DeleteObjects(List<string> imgUrlList)
        {
            List<string> keys = new List<string>();
            foreach (var url in imgUrlList)
            {
                var key = GetKey(url);
                keys.Add(key);
            }
            var deleteObjects = new DeleteObjectsRequest(_bucketName, keys);
            _client.DeleteObjects(deleteObjects);
        }

        private string GetUrl(string key)
        {
            var uri = _client.GeneratePresignedUri(_bucketName, key);
            return uri.GetLeftPart(UriPartial.Path);
        }

        private string GetKey(string url)
        {
            string key = "";
            if (url.Contains("http") || url.Contains("https"))
            {
                key = new Uri(url).LocalPath.TrimStart('/');
            }
            else
            {
                key = url.TrimStart('/');
            }
            return key;
        }
    }
}
